package com.ztgf.order.service.common;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.models.bo.pay.PayOrderSaveBO;
import com.ztgf.order.models.constant.OrderExpireTimeConstant;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.dto.pay.PayOrderLogDTO;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.service.async.IAsyncOrderService;
import com.ztgf.order.models.service.common.ICommonService;
import com.ztgf.order.models.service.pay.IPayOrderLogService;
import com.ztgf.order.models.service.pay.IPayOrderService;
import com.ztgf.order.models.vo.pay.PayOrderVO;
import com.ztgf.pay.models.dto.PayOrderDTO;
import com.ztgf.sys.models.dto.SysDictDTO;
import com.ztgf.sys.models.service.ISysDictService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: mxli
 * @Date: 2021-08-06 10:43
 **/
@DubboService
@Slf4j
public class CommonServiceImpl implements ICommonService {


    @Autowired
    @Lazy
    private IOrderInfoService orderInfoService;
    @Autowired
    @Lazy
    private IOrderStatusService orderStatusService;
    @Autowired
    private IOrderPayRelationService orderPayRelationService;
    @Autowired
    private IPayOrderLogService payOrderLogService;
    @Autowired
    private IOrderCommodityRelationService orderCommodityRelationService;
    @Autowired
    private IOrderExpirationDateService orderExpirationDateService;
    @Autowired
    private IOrderDeadlineRecordService orderDeadlineRecordService;
    @Autowired
    private IOrderContractRelationService orderContractRelationService;
    @DubboReference
    private ISysDictService sysDictService;
    @Autowired
    @Lazy
    private IAsyncOrderService asyncOrderService;
    @Autowired
    private IOrderReturnCommodityService orderReturnCommodityService;
    @Autowired
    private IPayOrderService payOrderService;
    @Autowired
    private IOrderPaymentTypeService orderPaymentTypeService;

    @Autowired
    private IOrderTimeRecordService orderTimeRecordService;
    @Resource
    private YmlConfig ymlConfig;

    @Override
    public Result saveReceive(Long orderId, boolean isCheckToken) {
        return saveReceive(orderId, isCheckToken, true);
    }

    @Override
    public Result saveReceive(Long orderId, boolean isCheckToken, boolean isFinish) {


        //解冻手续费
        Result result = new Result();
        try{
            result = orderStatusService.saveOrderReceive(orderId, isCheckToken, isFinish);


        } catch (ServiceException e){
            log.error("订单签收异常ServiceException: " + orderId, e);
            result.setCode(e.getCode());
            result.setMsg(e.getMessage());
        } catch (RuntimeException e){
            log.error("订单签收异常RuntimeException: " + orderId, e);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("签收失败");
        } catch (Exception e){
            log.error("订单签收异常Exception: " + orderId, e);
            result.setCode(CodeEnum.FAIL.getCode());
            result.setMsg("签收失败");
        }
        return result;
    }

    /**
     * 订单签收
     * @param bo
     * @param payOrderVO
     * @param userId
     * @param userName
     */
    @Override
    public void saveReceiveMoney(PayOrderSaveBO bo, PayOrderVO payOrderVO, Long userId, String userName) {
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(Long.parseLong(bo.getIds()));
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(Long.parseLong(bo.getIds()));
        if(orderInfoDTO == null || orderStatusDTO == null){
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        OrderPaymentTypeDTO typeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(orderInfoDTO.getId(), 1,2);
        if(typeDTO != null){//赊销订单 不处理
            log.error("-----赊销订单 不处理-------" + orderStatusDTO.getOrderState());
            if(orderStatusDTO.getOrderState() == 5 || orderStatusDTO.getOrderState() == 6 || orderStatusDTO.getOrderState() == 7){
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("order_id", orderInfoDTO.getId());
                List<OrderReturnCommodityDTO> returnCommodityDTOList = orderReturnCommodityService.selectList(wrapper);
                if(returnCommodityDTOList != null && returnCommodityDTOList.size() > 0){
                    for(OrderReturnCommodityDTO orderReturnCommodityDTO : returnCommodityDTOList){
                        try{
                            log.error("-----退款砍价服务费-------1");
                            if(orderReturnCommodityDTO.getPurchaseFeeMoneyScaleBackPrice().compareTo(BigDecimal.ZERO) > 0 && orderReturnCommodityDTO.getPurchaseFeeMoneyScalePriceBackStatus() != 2){
                                //退款砍价服务费
                                log.error("-----退款砍价服务费-------2");
                                payOrderService.saveRefundPurchaseFeeMoney(bo, orderReturnCommodityDTO, payOrderVO, userId, userName);
                            }
                        } catch (ServiceException e){
                            log.error("退款砍价服务费ServiceException: " + orderInfoDTO.getId(), e);

                        } catch (RuntimeException e){
                            log.error("退款砍价服务费RuntimeException: " + orderInfoDTO.getId(), e);

                        } catch (Exception e){
                            log.error("退款砍价服务费Exception: " + orderInfoDTO.getId(), e);

                        }

                        try{
                            log.error("-----退款佣金-------1");
                            //退款佣金
                            if(orderReturnCommodityDTO.getRefundCommissionMoney().compareTo(BigDecimal.ZERO) > 0 && orderReturnCommodityDTO.getRefundCommissionMoneyStatus() != 2){
                                PayOrderSaveBO saveBO = new PayOrderSaveBO();
                                saveBO.setIds(orderReturnCommodityDTO.getId().toString());
                                saveBO.setPayType(0);
                                saveBO.setType(19);
                                PayOrderVO savePayOrderVO = new PayOrderVO();
                                payOrderService.saveRefundCommissionMoney(saveBO, savePayOrderVO, userId, userName);
                            }
                        } catch (ServiceException e){
                            log.error("退款砍价服务费ServiceException: " + orderInfoDTO.getId(), e);

                        } catch (RuntimeException e){
                            log.error("退款砍价服务费RuntimeException: " + orderInfoDTO.getId(), e);

                        } catch (Exception e){
                            log.error("退款砍价服务费Exception: " + orderInfoDTO.getId(), e);

                        }

                    }
                }

            }

            return;
        }

        if(orderStatusDTO.getOrderState() != 5){
            throw new ServiceException(CodeEnum.FAIL_100002);
        }


        //解冻金额
        try{
            if(orderStatusDTO.getUnfreezeMoney().compareTo(BigDecimal.ZERO) > 0 && orderStatusDTO.getMoneyUnfreezeStatus() != 2){
                if(orderInfoDTO.getPayType() == 0){//1期
                    OrderPayRelationDTO oldOrderPayRelationDTO = orderPayRelationService.getByOrderIdAndPeriods(orderInfoDTO.getId(), 1);//一期
                    if(oldOrderPayRelationDTO.getPayType() == null || oldOrderPayRelationDTO.getPayType() == 0 || oldOrderPayRelationDTO.getPayType() == 1){
                        payOrderService.saveUnfreezeMoney(orderInfoDTO, oldOrderPayRelationDTO, orderStatusDTO.getUnfreezeMoney(), null, null);
                    }

                } else {
                    OrderPayRelationDTO oldOrderPayRelationDTO = orderPayRelationService.getByOrderIdAndPeriods(orderInfoDTO.getId(), 2);//二期
                    if (oldOrderPayRelationDTO.getPayType() == null || oldOrderPayRelationDTO.getPayType() == 0 || oldOrderPayRelationDTO.getPayType() == 1) {
                        payOrderService.saveUnfreezeMoney(orderInfoDTO, oldOrderPayRelationDTO, orderStatusDTO.getUnfreezeMoney(), null, null);
                    }
                }
            }
        } catch (ServiceException e){
            log.error("解冻金额异常ServiceException: " + orderInfoDTO.getId(), e);

        } catch (RuntimeException e){
            log.error("解冻金额RuntimeException: " + orderInfoDTO.getId(), e);

        } catch (Exception e){
            log.error("解冻金额Exception: " + orderInfoDTO.getId(), e);

        }


        try{
            if(orderInfoDTO.getLastCommissionMoney().compareTo(BigDecimal.ZERO) > 0 && orderStatusDTO.getCommissionMoneyPayStatus() != 2){
                log.error("----佣金支付----" );
                //佣金支付
                PayOrderSaveBO saveBO = new PayOrderSaveBO();
                saveBO.setType(1);
                saveBO.setIds(orderInfoDTO.getId().toString());
                saveBO.setPayType(0);
                payOrderService.savePayCommissionMoney(saveBO, payOrderVO, userId, userName);
                log.error("----佣金支付结束----" );
            }
        } catch (ServiceException e){
            log.error("佣金支付ServiceException: " + orderInfoDTO.getId(), e);

        } catch (RuntimeException e){
            log.error("佣金支付RuntimeException: " + orderInfoDTO.getId(), e);

        } catch (Exception e){
            log.error("佣金支付Exception: " + orderInfoDTO.getId(), e);

        }

    }

    /**
     * 合同签署成功
     * @param orderId
     * @return
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Result saveSellContactSuccess(Long orderId) {
        Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间


        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        OrderStatusDTO orderStatusDTO = orderStatusService.getByOrderId(orderId);
        if(orderInfoDTO == null || orderStatusDTO == null){
            log.error("回调错误savePaySuccess.orderInfoDTO.orderStatusDTO is null--->>>"  + orderId);
            throw new ServiceException(CodeEnum.FAIL_100002);
        }

        //买家未签订卖家不能签订
        if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_NO_SIGN.getCode()) {
            throw new ServiceException(CodeEnum.FAIL_ORDER_BUYER_NO_SIGN_CONTACT_310004);
        }
        //卖家已签订
        if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGN.getCode()) {
            throw new ServiceException(CodeEnum.FAIL_UPDATE_CONTACT_310006);
        }

        if(!(orderStatusDTO.getOrderState() == 1 || orderStatusDTO.getOrderState() == 2)){
            log.error("合同签订回调："+JSON.toJSONString(orderStatusDTO));
            OrderStatusDTO newOrderStatusDTO = new OrderStatusDTO();
            newOrderStatusDTO.setContactState(2);
            Wrapper wrapper = new EntityWrapper();
            wrapper.eq("order_id", orderId);
            wrapper.eq("contact_state", orderStatusDTO.getContactState());
            boolean flag = orderStatusService.update(newOrderStatusDTO, wrapper);
            if(!flag){
                log.error("合同状态修改失败!");
                throw new ServiceException(CodeEnum.FAIL_200022);
            }
            return new Result();
        }

        OrderPayRelationDTO oldOrderPayRelationDTO = orderPayRelationService.getByOrderIdAndPeriods(orderId, 1);//一期
        if(oldOrderPayRelationDTO == null ){
            log.error("回调错误savePaySuccess.orderInfoDTO.orderStatusDTO is null--->>>"  + orderId);
            throw new ServiceException(CodeEnum.FAIL_100002);
        }
        if(oldOrderPayRelationDTO.getPayType() == null){
            oldOrderPayRelationDTO.setPayType(1);
        }
        //更新签订日期
        OrderContractRelationDTO orderContractRelationDTO = orderContractRelationService.getByOrderId(orderId);
        OrderContractRelationDTO newOrderContractRelationDTO = new OrderContractRelationDTO();
        newOrderContractRelationDTO.setId(orderContractRelationDTO.getId());
        newOrderContractRelationDTO.setSignTime(DateUtils.getCurrentDateTime());
        boolean flag = orderContractRelationService.updateById(newOrderContractRelationDTO);//更新签订日期
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_100011);
        }


        List<OrderCommodityRelationDTO> orderCommodityRelationDTOList = orderCommodityRelationService.getByOrderId(orderId);
        int goodsProductionState = 0;
        boolean sendNotice = false;
        int orderStatus = orderStatusDTO.getOrderState();

        boolean unfreezeMoney = false;//是否解冻金额
        boolean payCommissionMoney = false;//是否支付佣金

        OrderPaymentTypeDTO typeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(orderId, 1,2);
        if(typeDTO != null){//赊销订单 不处理
            log.info("是否赊销订单----paymentType-----"+ JSON.toJSONString(typeDTO));
            orderStatus = OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode();//订单状态变为待发货

            //更新发货倒计时
            List<Integer> sendList = new ArrayList<Integer>();
            //处理多个商品中获取发货时间为最少的
            for(OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList){
                sendList.add(orderCommodityRelationDTO.getSendDays());
            }
            Integer sendDaysNum = Collections.max(sendList);
            //更新倒计时
            Date expireTime = DateUtils.addDay(currentDateTime, sendDaysNum);//过期时间
            OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
            if(orderExpirationDateDTO != null){
                OrderExpirationDateDTO newExpirationDateDTO = new OrderExpirationDateDTO();
                newExpirationDateDTO.setId(orderExpirationDateDTO.getId());
                newExpirationDateDTO.setExpirationTime(expireTime);
                newExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("id", orderExpirationDateDTO.getId());
                wrapper.eq("status", orderExpirationDateDTO.getStatus());

                String tiem = DateUtils.dateToStr(expireTime);
                log.info("orderid-------"+orderId+"--------待发货倒计时3----------"+tiem+"---------天数-----"+sendDaysNum);

                flag = orderExpirationDateService.update(newExpirationDateDTO, wrapper);//更新倒计时
                if(!flag){
                    throw new ServiceException(CodeEnum.FAIL_200022);
                }
            } else {
                OrderExpirationDateDTO newExpirationDateDTO = new OrderExpirationDateDTO();
                newExpirationDateDTO.setOrderId(orderId);
                newExpirationDateDTO.setId(ymlConfig.getPkId());
                newExpirationDateDTO.setExpirationTime(expireTime);
                newExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
                flag = orderExpirationDateService.insert(newExpirationDateDTO);//更新倒计时
                if(!flag){
                    throw new ServiceException(CodeEnum.FAIL_200022);
                }
            }

            // 待发货截止时间
            flag =  orderDeadlineRecordService.insert(orderId, 5, expireTime);
            if(!flag){
                throw new ServiceException(CodeEnum.FAIL_200022);
            }

            sendNotice = true;

        } else {
            //是否解冻或者支付佣金
            if(oldOrderPayRelationDTO.getPayState() == 2){
                if(orderInfoDTO.getPayType() == 1){ //支付方式 0全款、1分批
                    //解冻金额
                    if(oldOrderPayRelationDTO.getPayType() != null && oldOrderPayRelationDTO.getPayType() != 2){
                        unfreezeMoney = true;
                    }

                    goodsProductionState = 1;//待生成
                    orderStatus = OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode();//订单状态变为待付款

                    //处理备货过期倒计时
                    Date stockExpireTime = DateUtils.addDay(currentDateTime, orderCommodityRelationDTOList.get(0).getStockDays());//过期时间
                    OrderExpirationDateDTO newOrderExpirationDateDTO = new OrderExpirationDateDTO();
                    newOrderExpirationDateDTO.setOrderId(orderId);
                    newOrderExpirationDateDTO.setExpirationTime(stockExpireTime);
                    newOrderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode());
                    flag = orderExpirationDateService.updateByOrderId(newOrderExpirationDateDTO);//更新过期时间
                    if(!flag){
                        throw new ServiceException(CodeEnum.FAIL_100011);
                    }
                    // 记录备货截止时间
                    flag = orderDeadlineRecordService.insert(orderId, 9, stockExpireTime);
                    if(!flag){
                        throw new ServiceException(CodeEnum.FAIL_100011);
                    }

                } else {//全款
                    if(orderInfoDTO.getSellPayType() == 1){// 卖家店铺类型 0 担保交易 1先款交易
                        if(oldOrderPayRelationDTO.getPayType() != null && oldOrderPayRelationDTO.getPayType() != 2){
                            unfreezeMoney = true;
                            payCommissionMoney = true;
                        }
                    }
                    goodsProductionState = 2;//生成完成
                    orderStatus = OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode();//订单状态变为待发货

                    //更新发货倒计时
                    List<Integer> sendList = new ArrayList<Integer>();
                    //处理多个商品中获取发货时间为最少的
                    for(OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList){
                        sendList.add(orderCommodityRelationDTO.getSendDays());
                    }
                    Integer sendDaysNum = Collections.max(sendList);
                    //更新倒计时
                    Date expireTime = DateUtils.addDay(currentDateTime, sendDaysNum);//过期时间
                    OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
                    if(orderExpirationDateDTO != null){
                        OrderExpirationDateDTO newExpirationDateDTO = new OrderExpirationDateDTO();
                        newExpirationDateDTO.setId(orderExpirationDateDTO.getId());
                        newExpirationDateDTO.setExpirationTime(expireTime);
                        newExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
                        Wrapper wrapper = new EntityWrapper();
                        wrapper.eq("id", orderExpirationDateDTO.getId());
                        wrapper.eq("status", orderExpirationDateDTO.getStatus());

                        String tiem = DateUtils.dateToStr(expireTime);
                        log.info("orderid-------"+orderId+"--------待发货倒计时3----------"+tiem+"---------天数-----"+sendDaysNum);

                        flag = orderExpirationDateService.update(newExpirationDateDTO, wrapper);//更新倒计时
                        if(!flag){
                            throw new ServiceException(CodeEnum.FAIL_200022);
                        }
                    } else {
                        OrderExpirationDateDTO newExpirationDateDTO = new OrderExpirationDateDTO();
                        newExpirationDateDTO.setOrderId(orderId);
                        newExpirationDateDTO.setId(ymlConfig.getPkId());
                        newExpirationDateDTO.setExpirationTime(expireTime);
                        newExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_DELIVER_GOODS.getCode());
                        flag = orderExpirationDateService.insert(newExpirationDateDTO);//更新倒计时
                        if(!flag){
                            throw new ServiceException(CodeEnum.FAIL_200022);
                        }
                    }

                    // 待发货截止时间
                    flag =  orderDeadlineRecordService.insert(orderId, 5, expireTime);
                    if(!flag){
                        throw new ServiceException(CodeEnum.FAIL_200022);
                    }

                    sendNotice = true;

                }
            } else {

                //修改过期时间
                orderStatus = OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode();//订单状态变为待付款
                goodsProductionState = OrderStateEnum.ORDER_GOODS_NO_PRO.getCode();//未付款

                SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.SELLER_SIGN_TIME);//卖家签订合同后倒计时
                String time = sysDictDTO.getValue();
                Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间

                OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);

                OrderExpirationDateDTO newExpirationDateDTO = new OrderExpirationDateDTO();
                newExpirationDateDTO.setId(orderExpirationDateDTO.getId());
                newExpirationDateDTO.setExpirationTime(expireTime);
                newExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode());
                Wrapper wrapper = new EntityWrapper();
                wrapper.eq("id", orderExpirationDateDTO.getId());
                wrapper.eq("status", orderExpirationDateDTO.getStatus());

                String tiem = DateUtils.dateToStr(expireTime);
                log.info("orderid-------"+orderId+"--------待发货倒计时3----------"+tiem+"---------天数-----"+time);

                flag = orderExpirationDateService.update(newExpirationDateDTO, wrapper);//更新倒计时
                if(!flag){
                    throw new ServiceException(CodeEnum.FAIL_200022);
                }
                // 待付款截止时间
                flag =  orderDeadlineRecordService.insert(orderId, 4, expireTime);
                if(!flag){
                    throw new ServiceException(CodeEnum.FAIL_200022);
                }
            }
        }

        log.info("修改订单状态----orderstatus-----"+ orderStatus);

        //修改订单支付状态
        OrderStatusDTO newOrderStatusDTO = new OrderStatusDTO();
        newOrderStatusDTO.setOrderId(orderId);
        if(orderStatusDTO.getOrderState() == 1 || orderStatusDTO.getOrderState() == 2){
            newOrderStatusDTO.setOrderState(orderStatus);
        }

        if(goodsProductionState > 0){
            newOrderStatusDTO.setGoodsProductionState(goodsProductionState);
        }
        newOrderStatusDTO.setContactState(2);
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("order_id", orderId);
        wrapper.eq("order_state", orderStatusDTO.getOrderState());
        wrapper.eq("contact_state", orderStatusDTO.getContactState());
        wrapper.eq("goods_production_state", orderStatusDTO.getGoodsProductionState());
        log.info("卖家签订合同修改订单状态和合同状态orderId="+orderId+"---oldOrderState="+orderStatusDTO.getOrderState()+"--newOrderState="+orderStatus+"--oldContactState="+orderStatusDTO.getContactState()+"--newContactState="+newOrderStatusDTO.getContactState());
        flag = orderStatusService.update(newOrderStatusDTO, wrapper);
        if(!flag){
            log.error("合同状态修改失败!");
            throw new ServiceException(CodeEnum.FAIL_200022);
        }

        //保证数据一致性
        OrderPayRelationDTO newOldOrderPayRelationDTO = new OrderPayRelationDTO();
        newOldOrderPayRelationDTO.setRevision(oldOrderPayRelationDTO.getRevision() + 1);
        wrapper = new EntityWrapper();
        wrapper.eq("id", oldOrderPayRelationDTO.getId());
        wrapper.eq("pay_state", oldOrderPayRelationDTO.getPayState());
        flag = orderPayRelationService.update(newOldOrderPayRelationDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_200022);
        }

        try{
            if(unfreezeMoney){
                try {
                    //解冻金额
                    payOrderService.saveUnfreezeMoney(orderInfoDTO, oldOrderPayRelationDTO, oldOrderPayRelationDTO.getRealPayMoney(), null, null);
                }catch (ServiceException e){
                    log.error("卖家签合同 is error ", e);
                } catch (RuntimeException e){
                    log.error("卖家签合同RuntimeException is error ", e);
                } catch (Exception e){
                    log.error("卖家签合同Exception is error ", e);
                }

            }
            if(payCommissionMoney){
                try {
                    //支付佣金
                    PayOrderSaveBO saveBO = new PayOrderSaveBO();
                    saveBO.setType(1);
                    saveBO.setIds(orderId.toString());
                    saveBO.setPayType(0);
                    PayOrderVO payOrderVO = new PayOrderVO();
                    payOrderService.savePayCommissionMoney(saveBO, payOrderVO, null, null);
                }catch (ServiceException e){
                    log.error("卖家签合同 is error ", e);
                } catch (RuntimeException e){
                    log.error("卖家签合同RuntimeException is error ", e);
                } catch (Exception e){
                    log.error("卖家签合同Exception is error ", e);
                }

            }

        } catch (ServiceException e) {
            log.error("解冻佣金或者支付佣金错误", e);
        }

        if(sendNotice){
            Long sendShopId = orderInfoDTO.getBuyShopId();
            try {
                asyncOrderService.sendOrderNotice(sendShopId, orderId);
            } catch (Exception e){
                log.error("saveSellContactSuccess发送通知信息Exception is error ", e);
            }
        }

        return new Result();
    }

    @Override
    public Result saveReturnReceive(OrderReturnCommodityDTO dto) {
        try {
            orderReturnCommodityService.saveReceive(dto);
            //订单签收
            saveReceive(dto.getOrderId(),false, false);
        }catch (ServiceException e){
            log.error("退款签收 is error ", e);
            return new Result(CodeEnum.FAIL_ORDER_300010);
        } catch (RuntimeException e){
            log.error("退款签收RuntimeException is error ", e);
            return new Result(CodeEnum.FAIL_ORDER_300010);
        } catch (Exception e){
            log.error("退款签收Exception is error ", e);
            return new Result(CodeEnum.FAIL_ORDER_300010);
        }
        return new Result();
    }

    @Override
    public void saveOrder(PayOrderDTO orderDTO, PayOrderLogDTO logDTO) {

    }
}
